package com.jic.veteran.portal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jic.veteran.common.exception.ApiException;
import com.jic.veteran.mapper.CmsArticleInfoMapper;
import com.jic.veteran.model.CmsArticleInfo;
import com.jic.veteran.model.CmsArticleInfoExample;
import com.jic.veteran.portal.domain.CmsArticleQueryParam;
import com.jic.veteran.portal.service.ArticleService;

import java.util.Collections;
import java.util.List;

import com.jic.veteran.portal.service.UmsMemberCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 文章管理Service实现类
 * Created by macro on 2018/10/11.
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private CmsArticleInfoMapper articleInfoMapper;
    @Autowired
    private UmsMemberCacheService umsMemberCacheService;

    @Override
    public List<CmsArticleInfo> list(CmsArticleQueryParam queryParam) {
        String articleType = queryParam.getType();
        if (StrUtil.isEmpty(articleType)) {
            return Collections.emptyList();
        }
        List<CmsArticleInfo> cmsArticleInfoList = umsMemberCacheService.getCmsArticleInfoList(articleType);
        if (CollectionUtil.isEmpty(cmsArticleInfoList)) {
            CmsArticleInfoExample articleInfoExample = new CmsArticleInfoExample();
            CmsArticleInfoExample.Criteria criteria = articleInfoExample.createCriteria();
            criteria.andDeleteStatusEqualTo(false)
                    .andArticleTypeEqualTo(articleType.toLowerCase())
                    .andIsShowEqualTo(true);
            articleInfoExample.setOrderByClause("publish_time desc");
            cmsArticleInfoList = articleInfoMapper.selectByExample(articleInfoExample);
            if(!cmsArticleInfoList.isEmpty()) {
                umsMemberCacheService.setCmsArticleInfoList(cmsArticleInfoList);
            }
        }

        return cmsArticleInfoList;
    }

    @Override
    public CmsArticleInfo detail(Long id) {
        CmsArticleInfo articleInfo = articleInfoMapper.selectByPrimaryKey(id);
        if (articleInfo == null || articleInfo.getDeleteStatus() || !articleInfo.getIsShow()) {
            throw new ApiException("未找到详情信息");
        }
        return articleInfo;
    }

}
